import { ref } from 'vue'
import { defineStore } from 'pinia'
import type { PageConfig, LessonListItem } from '@/config/types'
import cfg from '@/config/config'
import api from '@/api/edu'
import type { StudySearchForm } from '@/config/forms'


export const useStudentLessonStore = defineStore('edu', () => {
  const loading = ref<boolean>(false)
  const search = ref<StudySearchForm>({
    accountId: 0,
    studentName: '',
    lessonId: 0,
    lessonTitle: '',
    openStartDate: '',
    openEndDate: '',
    page: 1,
    limit: cfg.pageLimit
  })
  const items = ref<LessonListItem[]>([])
  const pager = ref<PageConfig>({
    page: 1,
    pageSize: cfg.pageLimit,
    total: 0
  })

  async function loadItems() {
    loading.value = true
    try {
      const res = await api.getList(search.value)
      items.value = res.data
      pager.value = {
        page: res.page,
        pageSize: res.size,
        total: res.total
      }
      loading.value = false
    } catch (e) {
      loading.value = false
    }
  }

  async function changePage(page: number, pageSize: number) {
    search.value.page = page
    search.value.limit = pageSize
    await loadItems()
  }

  async function closeLesson(id: number) {
    loading.value = true
    try {
      const res = await api.close(id)
      loading.value = false
      return res.data
    } catch (e) {
      loading.value = false
    }
    return false
  }

  return {
    loading,
    search,
    items,
    pager,
    loadItems,
    changePage,
    closeLesson
  }
})
